package chapter13;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/21 14:52
 */
public class FileTest {
    public static void main(String[] args) {
        String filePath = "D:\\";
        File[] txtFiles = getTxtFiles(filePath);
        Arrays.stream(txtFiles).forEach((file) -> System.out.println(file.getName()));

        filePath = "D:\\我的坚果云";
        long byteSize = sizeOfDirectory(new File(filePath));
        double mSize = byteSize / 1024 / 1024.0;
        System.out.println("size of " + filePath + " is " + mSize + "MB");

    }

    private static void deleteRecursively(final File file) throws IOException {
        if (file.isFile()) {
            if (!file.delete()) {
                throw new IOException("Failed to delete " + file.getCanonicalPath());
            }
        } else if (file.isDirectory()) {
            // 递归删除目录下的文件及子目录
            for (File child : file.listFiles()) {
                deleteRecursively(child);
            }
            // 删除当前目录
            if (!file.delete()) {
                throw new IOException("Failed to delete " + file.getCanonicalPath());
            }
        }
    }

    private static Collection<File> findFile(final File directory, final String fileName) {
        List<File> files = new ArrayList<>();
        for (File file : directory.listFiles()) {
            if (file.isFile() && file.getName().equals(fileName)) {
                files.add(file);
            } else {
                findFile(file, fileName);
            }
        }

        return files;
    }

    private static long sizeOfDirectory(final File directory) {
        long size = 0;
        if (directory.isFile()) {
            return directory.length();
        } else {
            for (File file : directory.listFiles()) {
                size += sizeOfDirectory(file);
            }
        }

        return size;
    }

    private static File[] getTxtFiles(String dir) {
        File file = new File(dir);
        File[] files = file.listFiles((dir1, name) -> {
            if (name.endsWith(".txt")) {
                return true;
            }
            return false;
        });
        return files;
    }
}
